package netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.util.Scanner;

@Slf4j
public class EventLoppClient {
  public static void main(String[] args) throws InterruptedException {
    Bootstrap bt = new Bootstrap();
    NioEventLoopGroup group = new NioEventLoopGroup();
    bt.group(group);
    bt.channel(NioSocketChannel.class);
    bt.handler(new ChannelInitializer<NioSocketChannel>() {
      @Override
      protected void initChannel(NioSocketChannel ch) throws Exception {
        ch.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG));
        ch.pipeline().addLast(new StringEncoder());
      }
    });
    // 异步
    ChannelFuture channelFuture = bt.connect(new InetSocketAddress("localhost", 8080));
    // 主线程堵塞等待异步结果
    ChannelFuture sync = channelFuture.sync();
    // 主线程无阻塞执行
    Channel channel = channelFuture.channel();
    log.debug("channel = {}",channel);
    new Thread(()->{
      Scanner scanner = new Scanner(System.in);
      while (true) {
        String line = scanner.nextLine();
        if ("q".equals(line)) {
          channel.close();
          log.debug("channel closed");
          break;
        }
        channel.writeAndFlush(line);
      }
    },"input").start();

    ChannelFuture closedFuture = channel.closeFuture();

//    // 同步处理关闭
//    closedFuture.sync();
//    log.debug("close future closed");

      // 异步处理关闭
    closedFuture.addListener(new ChannelFutureListener() {
      @Override
      public void operationComplete(ChannelFuture channelFuture) throws Exception {
        log.debug("close future closed");
        group.shutdownGracefully();
      }
    });

//    // addListener异步处理监听结果
//    channelFuture.addListener(new ChannelFutureListener() {
//      @Override
//      public void operationComplete(ChannelFuture channelFuture) throws Exception {
//        Channel channel = channelFuture.channel();
//        log.debug("channel = {}",channel);
//      }
//    });
  }
}
